﻿using BackData;
using Domain.BOM;
using Domain.DTOs;
using Domain.DTOs.BOMs;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Team.API.Applocation.Command.BOM;


namespace Team.API.Controllers
{
    /// <summary>
    /// 物料清单控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BOMsController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IHttpContextAccessor httpContextAccessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">MediatR中介者</param>
        /// <param name="httpContextAccessor">HTTP上下文访问器</param>
        public BOMsController(IMediator mediator, IHttpContextAccessor httpContextAccessor)
        {
            this.mediator = mediator;
            this.httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 获取当前登录用户名
        /// 从HttpContext的Claims中获取用户名，如果不存在则返回"系统"
        /// </summary>
        /// <returns>当前登录用户名</returns>
        private string GetCurrentUserName()
        {
            try
            {
                var userName = httpContextAccessor.HttpContext?.User?.Identity?.Name;
                if (string.IsNullOrWhiteSpace(userName))
                {
                    // 尝试从Claims中获取用户名
                    userName = httpContextAccessor.HttpContext?.User?.Claims?
                        .FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Name)?.Value;
                }
                return string.IsNullOrWhiteSpace(userName) ? "系统" : userName;
            }
            catch
            {
                return "系统";
            }
        }

        /// <summary>
        /// 获取物料清单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<APIPaging<Bomtable>> GetBOM([FromQuery] GetBOMCommand request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 获取物料清单树结构
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<APIResult<List<BOMDTO>>> GetBOMTree([FromQuery] GetBOMTreeCommand request)
        {
            return mediator.Send(request);
        }

        /// <summary>
        /// BOM操作日志
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<OneNlogDTO>> BOMfinishedNlog([FromQuery] BOMfinishedNlogCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 获取BOM成品详情
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public Task<APIResult<BOMDTO>> GetBOMDetails([FromQuery] GetBOMDetailsCommand request)
        {
            return mediator.Send(request);
        }

        /// <summary>
        /// 获取BOM物料列表（排除成品，支持分页和查询）
        /// </summary>
        /// <param name="request">查询参数</param>
        /// <returns>分页结果</returns>
        [HttpGet]
        public Task<APIPaging<BOMListDTO>> GetBOMList([FromQuery] GetBOMListCommand request)
        {
            return mediator.Send(request);
        }

        /// <summary>
        /// 创建子级BOM
        /// </summary>
        /// <param name="request">创建命令</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public Task<APIResult<BOMDTO>> CreateChildBOM([FromBody] CreateChildBOMCommand request)
        {
            // 优先使用前端传来的当前登录人信息，如果为空则从HttpContext获取
            if (string.IsNullOrWhiteSpace(request.CurrentUserName))
            {
                request.CurrentUserName = GetCurrentUserName();
            }
            return mediator.Send(request);
        }

        /// <summary>
        /// 更新子级BOM
        /// </summary>
        /// <param name="request">更新命令</param>
        /// <returns>操作结果</returns>
        [HttpPut]
        public Task<APIResult<BOMDTO>> UpdateChildBOM([FromBody] UpdateChildBOMCommand request)
        {
            // 优先使用前端传来的当前登录人信息，如果为空则从HttpContext获取
            if (string.IsNullOrWhiteSpace(request.CurrentUserName))
            {
                request.CurrentUserName = GetCurrentUserName();
            }
            return mediator.Send(request);
        }

        /// <summary>
        /// 获取BOM操作日志列表（支持分页和搜索）
        /// 筛选条件：Category == "BOM" && IsDel == false
        /// </summary>
        /// <param name="request">查询参数</param>
        /// <returns>分页结果</returns>
        [HttpGet]
        public Task<APIPaging<BOMLogDTO>> GetBOMLogs([FromQuery] GetBOMLogsCommand request)
        {
            return mediator.Send(request);
        }

        /// <summary>
        /// 创建成品BOM
        /// </summary>
        /// <param name="request">创建命令</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public Task<APIResult<BOMDTO>> CreateProductBOM([FromBody] CreateProductBOMCommand request)
        {
            // 优先使用前端传来的当前登录人信息，如果为空则从HttpContext获取
            if (string.IsNullOrWhiteSpace(request.CurrentUserName))
            {
                request.CurrentUserName = GetCurrentUserName();
            }
            return mediator.Send(request);
        }

        /// <summary>
        /// 更新成品BOM
        /// </summary>
        /// <param name="request">更新命令</param>
        /// <returns>操作结果</returns>
        [HttpPut]
        public Task<APIResult<BOMDTO>> UpdateProductBOM([FromBody] UpdateProductBOMCommand request)
        {
            // 优先使用前端传来的当前登录人信息，如果为空则从HttpContext获取
            if (string.IsNullOrWhiteSpace(request.CurrentUserName))
            {
                request.CurrentUserName = GetCurrentUserName();
            }
            return mediator.Send(request);
        }

        /// <summary>
        /// 停用/启用成品BOM
        /// </summary>
        /// <param name="request">停用命令</param>
        /// <returns>操作结果</returns>
        [HttpPut]
        public Task<APIResult<BOMDTO>> DisableProductBOM([FromBody] DisableProductBOMCommand request)
        {
            // 优先使用前端传来的当前登录人信息，如果为空则从HttpContext获取
            if (string.IsNullOrWhiteSpace(request.CurrentUserName))
            {
                request.CurrentUserName = GetCurrentUserName();
            }
            return mediator.Send(request);
        }

        /// <summary>
        /// 软删除BOM
        /// </summary>
        /// <param name="request">删除命令</param>
        /// <returns>操作结果</returns>
        [HttpPost]

        public Task<APIResult<bool>> DeleteBOM([FromBody] DeleteBOMCommand request)
        {
            // 优先使用前端传来的当前登录人信息，如果为空则从HttpContext获取
            if (string.IsNullOrWhiteSpace(request.CurrentUserName))
            {
                request.CurrentUserName = GetCurrentUserName();
            }
            return mediator.Send(request);
        }
    }
}
